package com.redis.controller;

import com.redis.config.JedisUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;

import javax.annotation.Resource;

/**
 * @author chenzhangkun
 * @ClassName SimpleRateLimiter
 * @description: TODO
 * @date 2024年11月05日
 */
@RestController
@RequestMapping("/simple/rate-limit")
public class SimpleRateLimiter {

	@Resource
	private JedisUtils jedisUtils;

	/**
	 *
	 * @param userId y用户ID
	 * @param actionKey 场景key 比如访问view
	 * @param period 时长，比如60s
	 * @param maxCount 最大数量，10 60s内最大十次
	 * @return
	 */
	@GetMapping("/demo")
	public boolean isActionAllowed(@RequestParam("userId") String userId,@RequestParam("actionKey") String actionKey,
	                               @RequestParam("period") int period,@RequestParam("maxCount") int maxCount) {
		String key = String.format("hist:%s:%s", userId, actionKey);
		long nowTs = System.currentTimeMillis();
		Jedis jedis = jedisUtils.getJedis();
		Pipeline pipe = jedis.pipelined();
		// 多个命令
		pipe.multi();
		pipe.zadd(key, nowTs, "" + nowTs);
		// load出10s内的元素数量
		pipe.zremrangeByScore(key, 0, nowTs - period * 1000);
		Response<Long> count = pipe.zcard(key);
		// 给key设置过期时间
		pipe.expire(key, period + 1);
		// 执行多个命令
		pipe.exec();
		pipe.close();
		// 返回是否可以访问
		return count.get() <= maxCount;
	}

}
